from fastapi import FastAPI
from fastapi import APIRouter

from common import logger
# from ZtjDirImport import DirImport
from common.modules_helper import find_modules, import_string


def register_nestable_blueprint_for_log(
        app=None, project_name=None, api_name="", scan_name=None, key_attribute="", prefix=""
):
    """

    :param app: FastApi app对象
    :param project_name: 项目名称
    :param api_name: api路径
    :param scan_name: 扫描url的文件
    :param key_attribute: 匹配的路由
    :param prefix: 路由前缀
    :return:
    """
    if not app:
        import warnings
        warnings.warn('路由注册失败,需要传入Fastapi对象实例')
        return None
    if project_name:
        # include_packages 这个设置为True很关键，它包含了 检测 对于的_init__内的属性，这个对于外层的遍历的来说很关键
        modules = find_modules(f'{project_name}.{api_name}', include_packages=True, recursive=True)
        router_list = []
        for name in modules:
            module = import_string(name)
            # 只找某个模块开始的，避免无意义的其他扫描
            if scan_name is not None and not name.endswith(scan_name):
                continue

            if hasattr(module, key_attribute):
                router = getattr(module, key_attribute)
                router_list.append(router) if router not in router_list else ...

        def fn(router_obj):
            logger.debug(f"[Router] 注册路由{router_obj.tags}成功！！")
            app.include_router(router, prefix=prefix)

        list(map(lambda router_obj: fn(router_obj), router_list))

    else:
        import warnings
        warnings.warn('路由注册失败,外部项目名称还没定义')